const express = require('express')
const multer = require('multer')
const {UPLOAD_PATH} = require('../utils/constant')
const Result = require('../modules/Result')
const Book = require('../modules/Book')
const boom = require('boom')
const {decode} = require('../utils/index')
const bookService = require('../services/book')
const router = express.Router()


router.post('/upload',multer({dest: UPLOAD_PATH}).single('file'),(req,res,next)=>{
    if(!req.file || req.file.length===0){
        new Result('上传失败').fail(res)
    }else{
        const book = new Book(req.file)
        book.parse().then(book=>{
            new Result(book,'上传成功').success(res)
        }).catch(e=>{
            next(boom.badImplementation(e))
        })
        
    }
})

router.post('/create',(req,res,next)=>{
    const decoded = decode(req)

    if(decoded&&decoded.username){
        req.body.username = decoded.username
    }
    delete req.body.contents
    console.log(req.body)

    const book = new Book(null,req.body)


    bookService.insertBook(book).then((result)=>{
        new Result('图书添加成功').success(res)
    }).catch(err=>{
        next(boom.badImplementation(err))
    })


})

router.get('/get',(req,res,next)=>{
    const {fileName} = req.query
    if(!fileName){
        next(boom.badRequest(new Error('参数fileName不能为空')))
    }else{
        bookService.getBook(fileName).then((response)=>{
            new Result(response,'获取图书信息成功').success(res)
        }).catch(err=>{
            next(boom.badImplementation(err))
        })
    }
})

router.post('/update',(req,res,next)=>{

    const decoded = decode(req)

    if(decoded&&decoded.username){
        req.body.username = decoded.username
    }
    const book = new Book(null,req.body)
    bookService.updateBook(book).then(()=>{
        new Result('图书更新成功').success(res)
    })

})

router.get('/category',(req,res,next)=>{
    bookService.getCategory().then(category=>{
        new Result(category,'获取分类成功').success(res)
    }).catch(error=>{
        next(boom.badImplementation(error))
    })
})

router.get('/list',(req,res,next)=>{
    bookService.listBook(req.query).then(response=>{
        new Result(response,'图书列表获取成功').success(res)
    }).catch(err=>{
        next(boom.badImplementation(err))
    })
})

router.get('/delete',(req,res,next)=>{
    const fileName = req.query.fileName
    if(fileName){
        bookService.deleteBook(fileName).then(response=>{
            new Result('图书删除成功').success(res)
        }).catch(err=>{
            next(boom.badImplementation(err))
        })
    }else{
        next(boom.badRequest(new Error('参数fileName不能为空')))
    }

})

module.exports = router